<template>
  <view class="flex-col page">
    <!-- 主要内容区 -->
    <view class="content">
      <!-- 基础资料板块 -->
      <view class="section-list">
        <text class="section-title">基础资料</text>
        <view class="card">
          <view class="setting-item">
            <view class="setting-content">
              <image class="icon" src="../../static/images/3f7dd0e3bebcf4b2f4c2bc017a203930.png"/>
              <text class="font-default">头像</text>
            </view>
            <image class="avatar-small" :src="headsculpture" @click="changeimage()" />
          </view>

          <view class="divider"></view>

          <view class="setting-item">
            <view class="setting-content">
              <image class="icon" src="../../static/images/d9d64bffb1403fa8c5c1db8587d4991f.png"/>
              <text class="font-default">昵称</text>
            </view>
            <input class="input-field" v-model="nickname" @blur="saveNickname()" placeholder="请输入昵称"/>
          </view>
        </view>
      </view>

      <!-- 账号绑定板块 -->
      <view class="section-list">
        <text class="section-title">账号绑定</text>
        <view class="card">
          <view class="setting-item">
            <view class="setting-content">
              <image class="icon" src="../../static/images/weixin.png"/>
              <view class="bind-info">
                <text class="font-default">微信账号</text>
                <text class="bind-status" :class="{'bound': showUpImg}">{{showUpImg ? '已绑定' : '未绑定'}}</text>
              </view>
            </view>
            <evan-switch v-model="checked" :beforeChange="beforeChangePromise" @change="switchChange()" activeColor="#138f87" inactive-color="#EDEDED" style="zoom:.6"></evan-switch>
          </view>
        </view>
      </view>

      <!-- 密保资料板块 -->
      <view class="section-list">
        <text class="section-title">密保资料</text>
        <view class="card">
          <view class="setting-item" @click="deletetankuang()">
            <view class="setting-content">
              <image class="icon" src="../../static/images/shoujihao.png"/>
              <text class="font-default">手机号</text>
            </view>
            <view class="right-content">
              <text class="value-text">{{ userinfo.account_user ? userinfo.account_user.substring(0, 3) + '****' + userinfo.account_user.substring(7) : '' }}</text>
              <uni-icons type="right" size="14" color="#999"/>
            </view>
          </view>

          <view class="divider"></view>

          <view class="setting-item">
            <view class="setting-content">
              <image class="icon" src="../../static/images/019289ff2d46691bb9ef225e8884b3dc.png"/>
              <text class="font-default">注册时间</text>
            </view>
            <text class="value-text">{{ dateFormat(userinfo.registertime_user) }}</text>
          </view>
        </view>
      </view>

      <!-- 修改密码按钮 -->
      <view class="password-section">
        <button class="password-btn" @click="navTo('/pages/paschange/paschange')">修改密码</button>
      </view>
    </view>
  </view>
</template>

<script>
  import {_getuserinfo} from "@/service/user.js"
  //修改账号信息：如昵称
  import {_modifyname} from "@/service/user.js"
  export default {
    components: {},
    data() {
      return {
		checked:true,
		mlist_lIjKrOTp: [{nickname:''}, {name:''}, {gender:''}],
		showUpImg:true,
		userinfo:{},
		accountNum:'',
		password:'',
		nickname:'',
		imgList: [], //图片路径
		imgFileList: [], //图片文件
		imgNum: 1,
		image:'',
		headsculpture:''//头像
      };
    },
	onLoad(){
		let newdata;
		try {
			const value = uni.getStorageSync('userInfo');
			if (value != null) {
				this.accountNum = value.accountNum,
				this.password = value.password
			}
		} catch (e) {
			console.error(e);
		}
	},
	onShow() {
		this.init();
	},
    methods: {
		navTo(url){
					  uni.navigateTo({
					  	url:url,
					  })
		},
		dateFormat(registertime) {
		    let date = new Date(registertime);
		    let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();
			let hours = date.getHours();
			let minutes = date.getMinutes();
			let seconds = date.getSeconds();
		    return year + "-" + month + "-" + day;
		},
		switchChange(){
			this.showUpImg=!this.showUpImg
		},
		beforeChange(e) {
				uni.showToast({
					title: '开关切换被拦截'
				})
				return false
				
			},
		beforeChangePromise(e) {
			return new Promise((resolve, reject) => {
				uni.showModal({
					title: '提示',
					content: `你确定要${e?'绑定':'解除绑定'}吗`,
					success: (res) => {
						if (res.confirm) {
							resolve()
						} else if (res.cancel) {
							reject()
						}
					}
				})
			})
		},
		async init(){
			let data = {
				account_user:this.accountNum,
				password_user:this.password
			}
			let res = await _getuserinfo(data);
			console.log(res.data);
			this.userinfo = res.data
			this.nickname=this.userinfo.nickname_user
			this.headsculpture=this.userinfo.photo_user
		},

		modifynickname(){
			
		},
		//修改昵称
		async saveNickname(){
			let data={
				account_user:this.userinfo.account_user,
				nickname_user:this.nickname
			}
			let res=await _modifyname(data);
			console.log(res.data);
		},
		changeimage(){
        this.ifShow = false;
        let s = this.imgNum - this.imgList.length;
        //打开本地相册选择图片
        uni.chooseImage({
          count: s,
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          success: (res) => {
            console.log('选择图片成功:', res);
            if (s >= res.tempFilePaths.length) {
              for (let v of res.tempFilePaths) {
                this.imgList.push(v);
              }
              for (let v of res.tempFiles) {
                this.imgFileList.push(v);
              }
            }
            console.log('准备上传图片');
            this.uploadImage()
          },
        });
      },
      async uploadImage() {
        try {
          const imgFile = this.imgFileList[0]; // 获取第一张图片
          const tempFilePath = imgFile.path;
          console.log('开始上传图片:', tempFilePath);

          const res = await new Promise((resolve, reject) => {
            uni.uploadFile({
              url: 'http://43.142.102.167:8088/common/image',
              filePath: tempFilePath,
              name: 'image',
              formData: {
                shopTalkNumber: 1 // 上传一张图片时设置数量为1
              },
              success: (res) => resolve(res),
              fail: (error) => reject(error)
            });
          });

          console.log('上传成功后的响应数据:', res.data); // 上传成功后的返回数据
          const responseData = JSON.parse(res.data);
          console.log('解析后的响应数据:', responseData.data);
          this.image = responseData.data; // 将返回的单个图片数据作为数组元素
          console.log('当前图片路径:', this.image)
          console.log('上传成功');
          this.saveheadsculpture()

        } catch (error) {
          console.error('上传图片失败:', error);
          // this.$api.msg('上传图片失败');
        }
      },
		async saveheadsculpture(){
			console.log(this.image)
			let data={
				account_user:this.userinfo.account_user,
				photo_user:this.image
			}
			let res=await _modifyname(data);
			console.log(res);
			if(res.flag==true){
				this.headsculpture=this.image
			}
		},
		deletetankuang(){
				  uni.showModal({
				  		title: '提示',
				  		// 提示文字
				  		content: '是否更换已绑定的手机号',
				  		// 取消按钮的文字自定义
				  		cancelText: "取消",
				  		// 确认按钮的文字自定义
				  		confirmText: "确定",
				  		//删除字体的颜色
				  		confirmColor:'red',
				  		//取消字体的颜色
				  		cancelColor:'#000000',
				  		success:(res)=>{
				  		if (res.confirm) {
							 this.navTo('/pages/xiugaishoujihao/xiugaishoujihao');
				  		} 
				  	}
				  })
			  }
	},
  };
  
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f7f7f7;
}

.header {
  background: linear-gradient(180deg, #44cdbd 0%, #239f97 100%);
  padding: 120rpx 32rpx 80rpx;
}

.user-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 32rpx;
  margin-top: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

  .user-info {
    display: flex;
    align-items: center;

    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 60rpx;
      border: 4rpx solid #fff;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    .info-content {
      flex: 1;
      margin-left: 24rpx;

      .nickname {
        font-size: 36rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 8rpx;
      }

      .account {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.content {
  margin-top: -20rpx;
  border-radius: 20rpx 20rpx 0 0;
  background: #f7f7f7;
  min-height: 100vh;
  padding: 20rpx 0;
}

.section-list {
  margin-top: 20rpx;
  padding: 0 32rpx;
  margin-bottom: 32rpx;

  .section-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
    padding-left: 16rpx;
  }

  .card {
    background: #fff;
    border-radius: 12rpx;
    padding: 0 32rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
  }

  .setting-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    margin: 0 -32rpx;
    transition: background-color 0.25s;

    &:active {
      background-color: #f0f0f0;
    }

    .setting-content {
      display: flex;
      align-items: center;

      .icon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 24rpx;
      }

      .font-default {
        font-size: 30rpx;
        color: #333;
      }

      .bind-info {
        display: flex;
        flex-direction: column;
        
        .bind-status {
          font-size: 24rpx;
          color: #999;
          margin-top: 4rpx;
          
          &.bound {
            color: #138f87;
          }
        }
      }
    }

    .avatar-small {
      width: 70rpx;
      height: 70rpx;
      border-radius: 35rpx;
      border: 2rpx solid #eee;
    }

    .input-field {
      flex: 1;
      text-align: right;
      font-size: 30rpx;
      color: #333;
      padding: 0 20rpx;
    }

    .right-content {
      display: flex;
      align-items: center;
      
      .value-text {
        font-size: 28rpx;
        color: #666;
        margin-right: 16rpx;
      }
    }
  }

  .divider {
    height: 1rpx;
    background-color: #f5f5f5;
    margin: 0 -32rpx;
  }
}

.password-section {
  padding: 32rpx;
  margin-top: 40rpx;

  .password-btn {
    background: #138f87;
    color: #fff;
    border-radius: 12rpx;
    font-size: 32rpx;
    padding: 24rpx 0;
    text-align: center;
    border: none;
    transition: opacity 0.25s;

    &:active {
      opacity: 0.8;
    }
  }
}
</style>